package com.gitee.wsl.compose.data.store

import androidx.compose.runtime.Composable
import androidx.compose.runtime.ProvidableCompositionLocal
import androidx.compose.runtime.ReadOnlyComposable
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.platform.LocalInspectionMode
import com.gitee.wsl.compose.state.S
import com.gitee.wsl.data.store.StoreServer
import com.gitee.wsl.data.store.cache.MemoryStoreServer
import kotlinx.coroutines.CoroutineScope

/**
 * You can call `LocalDataSaver.current` inside a [androidx.compose.runtime.Composable] to
 * get the instance you've provided. You can call `readData` and `saveData` then.
 */
var LocalDataSaver: ProvidableCompositionLocal<StoreServer> = staticCompositionLocalOf {
    MemoryStoreServer.defaultServer
}


/**
 * Get the [DataSaverInterface] instance, if [LocalInspectionMode.current] is true, return [DataSaverInMemory] instead
 * which supports preview in Android Studio
 * @return DataSaverInterface
 */
@Composable
@ReadOnlyComposable
fun getLocalDataSaverInterface() = if (LocalInspectionMode.current) MemoryStoreServer.defaultServer else LocalDataSaver.current

@Composable
inline fun <reified T> S.storeState(
    key: String,
    initialValue: T,
    savePolicy: SavePolicy = SavePolicy.IMMEDIATELY,
    async: Boolean = true,
    senseExternalDataChange: Boolean = false,
    coroutineScope: CoroutineScope? = null
) = rememberStoreSaverState(
    key,
    initialValue,
    savePolicy,
    async,
    senseExternalDataChange,
    coroutineScope
)